package com.balabala.gym_system.interceptor;

import com.balabala.constant.TokenConstant;
import com.balabala.dto.UserInfoDto;
import com.balabala.gym_system.pojo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Slf4j
public class MyHandlerInterceptor implements HandshakeInterceptor {
    @Autowired
    private  RedisTemplate redisTemplate;
    /**
     * 握手之前，若返回false，不建立连接
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {

        //讲用户的用户名放入了websocket的session中
        String path = serverHttpRequest.getURI().getPath();
        String[] pa = path.split("/");
        String token=pa[2];
        System.out.println(token);
        //传token加key查redis信息
        UserInfoDto  userInfoDto = (UserInfoDto) redisTemplate.boundValueOps(TokenConstant.USER_TOKEN_SECRET+token).get();
        System.out.println("用户信息"+userInfoDto.toString());

       //把用户名和id放入session的map集合中
       map.put("username",userInfoDto.getNickname());
       map.put("uid",userInfoDto.getId());

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        log.info("握手成功...");
    }

}